<?php

require_once('pgpdoconnect.php');
require_once('biocase.php');
require_once('hispid5tocsv.php');
require_once('avhdb.php');
require_once('biocasediagnostic.php');

// get config
$config = array();
$config['core'] = array();
$handle = fopen('config/config_avh_db_core.csv', 'r');
while (!feof($handle))
    $config['core'][] = fgetcsv ($handle);
fclose($handle);

$config['extension'] = array();
$handle = fopen('config/config_avh_db_extension.csv', 'r');
while (!feof($handle))
    $config['extension'][] = fgetcsv ($handle);
fclose($handle);

$offset = 0;

$select = "SELECT count(*)
    FROM core c
    WHERE c.\"institutionCode\"='MEL'
    AND c.\"scientificName\" IS NULL";
$query = $pgdb->query($select);
$row = $query->fetch(PDO::FETCH_NUM);
$count = $row[0];


while ($offset < $count) {
    $select = "SELECT c.\"collectionCode\", c.\"catalogNumber\"
        FROM core c
        WHERE c.\"institutionCode\" LIKE 'AD%'
        AND c.\"scientificName\" IS NULL
        LIMIT 500 OFFSET $offset";
    $query = $pgdb->query($select);
    
    $sourceInstitutionIDs = array();
    $unitIDs = array();
    while ($row = $query->fetch(PDO::FETCH_OBJ)) {
        $sourceInstitutionIDs[] = $row->collectionCode;
        $unitIDs[] = $row->catalogNumber;
    }
    
    $sourceInstitutionIDs = array_unique($sourceInstitutionIDs);
    $sources = array();
    foreach ($sourceInstitutionIDs as $key=>$value) {
        $source = array();
        $source['Name'] = $value;
        $units = array();
        foreach ($unitIDs as $unit)
            $units[] = '<value>' . $unit . '</value>';
        $source['Units'] = implode('', $units);
        $sources[] = $source;
    }
    
    $filter = '<or>';
    foreach ($sources as $source ) {
        $filter .= '<and>';
        $filter .= "<equals path='/DataSets/DataSet/Units/Unit/SourceInstitutionID'>" . $source['Name'] . "</equals>";
        $filter .= "<in path='/DataSets/DataSet/Units/Unit/UnitID'>" . $source['Units'] . '</in>';
        $filter .= '</and>';
    }
    $filter .= '</or>';
    
    $biocase = new BioCase('http://www.envappsqa.sa.gov.au/biocase2/pywrapper.cgi', 'adherb', 'http://www.tdwg.org/schemas/abcd/2.06', FALSE, 0, 500);
    $xml = $biocase->biocaseGeneralFilter($filter);
    
    file_put_contents('xml/AD_0000000.xml', $xml);
    
    /*$doc = new DOMDocument('1.0', 'UTF-8');
    $doc->loadXML($xml);
    
    $diag = new BiocaseDiagnostic($pgdb, $doc, 1);
    $diag->diagnose();
    
    $dehispidator = new Hispid5ToCsv();
    $data['core'] = $dehispidator->parseHISPID5($doc);
    $data['extension'] = $dehispidator->DeterminationHistory($doc);

    $upload = new AvhDb($pgdb, $data, $config);
    $upload->uploadCoreData(FALSE);
    $upload->uploadExtensionData();
    */
    $offset += 500;
}

?>
